package myspringbootstart.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

@Component
public class WebInit implements WebApplicationInitializer, ApplicationContextAware {
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
//     <servlet>
//        <servlet-name>app</servlet-name>
//        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
//        <init-param>
//            <param-name>contextConfigLocation</param-name>
//            <param-value></param-value>
//        </init-param>
//        <load-on-startup>1</load-on-startup>
//    </servlet>
        ServletRegistration.Dynamic dynamic = servletContext.addServlet("app",getServlet());
        dynamic.setLoadOnStartup(1);
//  <servlet-mapping>
//    <servlet-name>dispatcher</servlet-name>
//    <url-pattern>/</url-pattern>
//  </servlet-mapping>
        dynamic.addMapping("/");
    }

    public static DispatcherServlet getServlet(){
        return context.getBean(DispatcherServlet.class);
    }
}
